package net.suncaper.psychological.web.controller;

import net.suncaper.psychological.common.framework.simplemvc.RequestMapping;
import net.suncaper.psychological.common.utils.Result;
import net.suncaper.psychological.common.utils.MyDbUtil;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 咨询师控制器
 */
@RequestMapping("/api/consultant")
public class ConsultantController {

    /**
     * 获取咨询师负责的学生列表
     */
    @RequestMapping("/students")
    public void getMyStudents(HttpServletRequest request, HttpServletResponse response) {
        try {
            String consultantId = request.getParameter("consultantId");
            
            if (consultantId == null) {
                Result.error("咨询师ID不能为空").writeTo(response);
                return;
            }
            
            // 查询咨询师负责的学生（只查询咨询类型，通过appointment.duty_id -> duty_schedule.user_id关联）
            String sql = "SELECT " +
                        "a.id as appointment_id, " +
                        "a.student_id, " +
                        "u.username as student_username, " +
                        "u.name as student_name, " +
                        "u.phone as student_phone, " +
                        "u.gender as student_gender, " +
                        "u.extra_info as student_extra_info, " +
                        "a.scheduled_time, " +
                        "a.scheduled_place, " +
                        "a.status as appointment_status, " +
                        "a.type as appointment_type, " +
                        "ds.user_id as consultant_id, " +
                        "(SELECT COUNT(*) FROM visit_record vr WHERE vr.appointment_id = a.id AND vr.type = 'CONSULT') as consult_count, " +
                        "(SELECT vr.conclusion FROM visit_record vr WHERE vr.appointment_id = a.id AND vr.type = 'CONSULT' ORDER BY vr.visit_time DESC LIMIT 1) as latest_conclusion " +
                        "FROM appointment a " +
                        "INNER JOIN duty_schedule ds ON a.duty_id = ds.id " +
                        "INNER JOIN user u ON a.student_id = u.id " +
                        "WHERE ds.user_id = ? " +
                        "AND ds.role = 'CONSULTANT' " +
                        "AND a.type = 'CONSULT' " +
                        "AND a.status IN ('APPROVED', 'COMPLETED') " +
                        "ORDER BY a.scheduled_time DESC";
            
            System.out.println("咨询师查询SQL: " + sql);
            System.out.println("咨询师ID参数: " + consultantId);
            
            List<Map<String, Object>> students = MyDbUtil.executeQueryMap(sql, consultantId);
            
            // 处理额外信息
            for (Map<String, Object> student : students) {
                String extraInfo = (String) student.get("student_extra_info");
                if (extraInfo != null && !extraInfo.isEmpty()) {
                    try {
                        Map<String, Object> extra = JSON.parseObject(extraInfo, Map.class);
                        student.put("department", extra.get("department"));
                        student.put("class", extra.get("class"));
                    } catch (Exception e) {
                        System.err.println("解析学生额外信息失败: " + e.getMessage());
                    }
                }
            }
            
            Result.success(students, "获取学生列表成功").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("获取学生列表失败: " + e.getMessage()).writeTo(response);
        }
    }

    /**
     * 获取学生的咨询记录
     */
    @RequestMapping("/records")
    public void getStudentRecords(HttpServletRequest request, HttpServletResponse response) {
        try {
            String appointmentId = request.getParameter("appointmentId");
            
            if (appointmentId == null) {
                Result.error("预约ID不能为空").writeTo(response);
                return;
            }
            
            String sql = "SELECT vr.*, " +
                        "a.scheduled_time, " +
                        "a.scheduled_place, " +
                        "a.type as appointment_type, " +
                        "u.name as student_name " +
                        "FROM visit_record vr " +
                        "LEFT JOIN appointment a ON vr.appointment_id = a.id " +
                        "LEFT JOIN user u ON a.student_id = u.id " +
                        "WHERE vr.appointment_id = ? " +
                        "ORDER BY vr.visit_time ASC";
            
            List<Map<String, Object>> records = MyDbUtil.executeQueryMap(sql, appointmentId);
            
            Result.success(records, "获取咨询记录成功").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("获取咨询记录失败: " + e.getMessage()).writeTo(response);
        }
    }

    /**
     * 提交咨询记录
     */
    @RequestMapping("/submit-record")
    public void submitConsultRecord(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String jsonData = getRequestBody(request);
            System.out.println("收到咨询记录数据: " + jsonData);
            
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            // 验证必填字段
            if (data.get("appointment_id") == null || data.get("visitor_id") == null || 
                data.get("visit_time") == null || data.get("conclusion") == null) {
                Result.error("必填字段不能为空").writeTo(response);
                return;
            }
            
            // 检查是否超过8次咨询
            String checkSql = "SELECT COUNT(*) as count FROM visit_record WHERE appointment_id = ? AND type = 'CONSULT'";
            List<Map<String, Object>> countResult = MyDbUtil.executeQueryMap(checkSql, data.get("appointment_id"));
            int currentCount = ((Number) countResult.get(0).get("count")).intValue();
            
            if (currentCount >= 8) {
                Result.error("已达到最大咨询次数(8次)，无法继续添加记录").writeTo(response);
                return;
            }
            
            // 插入咨询记录
            String sql = "INSERT INTO visit_record(appointment_id, visitor_id, type, visit_time, risk_level, problem_type, conclusion, note) " +
                        "VALUES (?, ?, 'CONSULT', ?, ?, ?, ?, ?)";
            
            int result = MyDbUtil.executeUpdate(sql, 
                data.get("appointment_id"),
                data.get("visitor_id"),
                data.get("visit_time"),
                data.get("risk_level"),
                data.get("problem_type"),
                data.get("conclusion"),
                data.get("note")
            );
            
            // 如果结论是"结案"，更新预约状态为COMPLETED
            if ("结案".equals(data.get("conclusion"))) {
                String updateSql = "UPDATE appointment SET status = 'COMPLETED' WHERE id = ?";
                MyDbUtil.executeUpdate(updateSql, data.get("appointment_id"));
            }
            
            response.setContentType("application/json;charset=UTF-8");
            if (result > 0) {
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":\"咨询记录提交成功\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("咨询记录提交成功，返回: " + jsonResponse);
            } else {
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"咨询记录提交失败\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("咨询记录提交失败，返回: " + jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"提交咨询记录时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 提前结案
     */
    @RequestMapping("/close-case")
    public void closeCase(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            Long appointmentId = Long.valueOf(data.get("appointment_id").toString());
            Long visitorId = Long.valueOf(data.get("visitor_id").toString());
            String closeReason = (String) data.get("close_reason");
            
            // 插入结案记录
            String sql = "INSERT INTO visit_record(appointment_id, visitor_id, type, visit_time, risk_level, problem_type, conclusion, note) " +
                        "VALUES (?, ?, 'CONSULT', NOW(), 'LOW', '提前结案', '结案', ?)";
            
            int result = MyDbUtil.executeUpdate(sql, appointmentId, visitorId, closeReason);
            
            // 更新预约状态为COMPLETED
            String updateSql = "UPDATE appointment SET status = 'COMPLETED' WHERE id = ?";
            MyDbUtil.executeUpdate(updateSql, appointmentId);
            
            response.setContentType("application/json;charset=UTF-8");
            if (result > 0) {
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":\"提前结案成功\"}";
                response.getWriter().write(jsonResponse);
            } else {
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"提前结案失败\"}";
                response.getWriter().write(jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"提前结案时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 读取请求体中的JSON数据
     */
    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }
} 